class ApplicationController < ActionController::Base
  include MenusHelper, ApplicationHelper

  protect_from_forgery with: :exception
  before_action :prepare_exception_notifier
  before_action :set_locale, :check_login
  before_action :set_per_page, :load_menu, :set_current_menu
  helper_method :current_user, :per_page, :request_referer


  def current_user
    return nil if session[:current_user_id].blank? || (session[:expire_at] && Time.parse(session[:expire_at]) < Time.now)
    @current_user ||= User.find_by_id(session[:current_user_id])
  end

  def per_page
    session[:per_page] || 20
  end


  def check_login
    if current_user.blank?
      redirect_to login_path
    end
  end

  def set_locale
    session[:locale] = params[:locale] unless params[:locale].blank?
    session[:locale] = 'zh-CN' unless I18n.locale_available?(session[:locale])
    I18n.locale = session[:locale]
  end

  def set_current_user
    Session.set_user current_user if current_user
  end

  def set_per_page
    session[:per_page] = params[:per_page].to_i if params[:per_page].to_i.positive?
  end

  def clear_session
    session[:current_user_id] = nil
    session[:expired_at] = nil
    @current_user = nil
  end

  # 引用页
  def request_referer
    request.env['HTTP_REFERER'] || root_path
  end

  def error_notice(msg)
    show_js_notice(msg, type: :error)
  end

  def show_js_notice(msg, arg = {})
    if arg[:type].to_s == 'error'
      if msg.is_a?(ApplicationRecord) && !msg.errors.values.empty?
        _msg = "#{ts(:operation, :fail)}！<br/>#{msg.errors.full_messages.join('<br/>')}"
      end
      render js: "error_notice(#{(_msg || msg).to_json})"
    else
      flash[:notice] = msg
      respond_to do |format|
        format.html { redirect_to request_referer }
        format.js { render js: "Turbolinks.visit(#{request_referer.to_json})" }
      end
    end
  end

  def prepare_exception_notifier
    h = { ip: request.ip }
    h.merge!(params: params.to_json ) rescue {}
    h.merge!(current_user: current_user.to_json(only: [:name,:id, :username])) if current_user
    request.env['exception_notifier.exception_data'] = h
  end
end
